package com.ics.atable.chat.config;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;

@MappedTypes(float[].class)
@MappedJdbcTypes(JdbcType.BLOB)
public class FloatArrayToBlobTypeHandler extends BaseTypeHandler<float[]> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, float[] parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null) {
            // 将float[]转换为byte[]
            byte[] bytes = new byte[parameter.length * 4];
            for (int j = 0; j < parameter.length; j++) {
                int bits = Float.floatToIntBits(parameter[j]);
                bytes[j * 4] = (byte) (bits & 0xFF);
                bytes[j * 4 + 1] = (byte) ((bits >> 8) & 0xFF);
                bytes[j * 4 + 2] = (byte) ((bits >> 16) & 0xFF);
                bytes[j * 4 + 3] = (byte) ((bits >> 24) & 0xFF);
            }
            ps.setBytes(i, bytes);
        } else {
            ps.setNull(i, jdbcType.TYPE_CODE);
        }
    }

    @Override
    public float[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        byte[] bytes = rs.getBytes(columnName);
        return bytesToFloatArray(bytes);
    }

    @Override
    public float[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        byte[] bytes = rs.getBytes(columnIndex);
        return bytesToFloatArray(bytes);
    }

    @Override
    public float[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        byte[] bytes = cs.getBytes(columnIndex);
        return bytesToFloatArray(bytes);
    }

    private float[] bytesToFloatArray(byte[] bytes) {
        if (bytes == null) return null;
        float[] floats = new float[bytes.length / 4];
        for (int i = 0; i < floats.length; i++) {
            int bits = (bytes[i * 4] & 0xFF) |
                      ((bytes[i * 4 + 1] & 0xFF) << 8) |
                      ((bytes[i * 4 + 2] & 0xFF) << 16) |
                      ((bytes[i * 4 + 3] & 0xFF) << 24);
            floats[i] = Float.intBitsToFloat(bits);
        }
        return floats;
    }
}
